<template>
  <div>
    <el-card>
      <div class="mb-4">
        <el-button type="primary" @click="handleAdd">新增调班申请</el-button>
      </div>
      
      <el-table :data="shiftList" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="申请人">
          <template #default="{ row }">
            {{ userFormatter(row.applicantId) }}
          </template>
        </el-table-column>
        <el-table-column label="调班对象">
          <template #default="{ row }">
            {{ userFormatter(row.targetUserId) }}
          </template>
        </el-table-column>
        <el-table-column prop="shiftDate" label="调班日期" />
        <el-table-column prop="reason" label="调班原因" />
        <el-table-column prop="status" label="状态">
          <template #default="{ row }">
            <el-tag :type="statusType(row.status)">
              {{ statusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" />
        <el-table-column label="操作" width="180">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="dialogTitle">
      <el-form :model="form" :rules="rules" ref="formRef">
        <el-form-item label="申请人ID" prop="applicantId">
          <el-input v-model="form.applicantId" />
        </el-form-item>
        <el-form-item label="调班对象ID" prop="targetUserId">
          <el-input v-model="form.targetUserId" />
        </el-form-item>
        <el-form-item label="调班日期" prop="shiftDate">
          <el-date-picker 
            v-model="form.shiftDate" 
            type="date" 
            placeholder="选择调班日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="调班原因" prop="reason">
          <el-input v-model="form.reason" type="textarea" />
        </el-form-item>
        <el-form-item label="状态" prop="status" v-if="!isAdd">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="待审批" :value="0" />
            <el-option label="已通过" :value="1" />
            <el-option label="已拒绝" :value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  listShiftchange, 
  addShiftchange, 
  updateShiftchange, 
  delShiftchange 
} from '@/api/shiftchange'
import { listUsertable } from '@/api/usertable'

const shiftList = ref([])
const userMap = ref({})
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isAdd = ref(true)
const formRef = ref(null)

const form = reactive({
  id: null,
  applicantId: null,
  targetUserId: null,
  shiftDate: '',
  reason: '',
  status: 0
})

const rules = {
  applicantId: [{ required: true, message: '请输入申请人ID', trigger: 'blur' }],
  targetUserId: [{ required: true, message: '请输入调班对象ID', trigger: 'blur' }],
  shiftDate: [{ required: true, message: '请选择调班日期', trigger: 'change' }],
  reason: [{ required: true, message: '请输入调班原因', trigger: 'blur' }]
}

// 状态文本转换
const statusText = (status) => {
  const map = {
    0: '待审批',
    1: '已通过',
    2: '已拒绝'
  }
  return map[status] || '未知'
}

// 状态标签类型
const statusType = (status) => {
  const map = {
    0: 'warning',
    1: 'success',
    2: 'danger'
  }
  return map[status] || ''
}

// 获取调班记录列表
const getShiftList = async () => {
  try {
    const response = await listShiftchange()
    if (response) {
      shiftList.value = response
    } else {
      ElMessage.error('获取调班列表失败: 数据格式异常')
    }
  } catch (error) {
    ElMessage.error(`获取调班列表失败: ${error.message}`)
  }
}

// 新增调班记录
const handleAdd = () => {
  dialogTitle.value = '新增调班申请'
  isAdd.value = true
  Object.assign(form, {
    id: null,
    applicantId: null,
    targetUserId: null,
    shiftDate: '',
    reason: '',
    status: 0
  })
  dialogVisible.value = true
}

// 编辑调班记录
const handleEdit = (row) => {
  dialogTitle.value = '编辑调班申请'
  isAdd.value = false
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除调班记录
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该调班记录?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    await delShiftchange(row.id)
    ElMessage.success('删除成功')
    getShiftList()
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 提交表单
const submitForm = async () => {
  await formRef.value.validate()
  try {
    if (isAdd.value) {
      await addShiftchange(form)
      ElMessage.success('新增成功')
    } else {
      await updateShiftchange(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getShiftList()
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

// 获取用户数据
const fetchUsers = async () => {
  try {
    const response = await listUsertable()
    if (response) {
      response.forEach(user => {
        userMap.value[user.id] = user.userName
      })
    }
  } catch (error) {
    ElMessage.error(`获取用户列表失败: ${error.message}`)
  }
}

// 用户ID转用户名
const userFormatter = (userId) => {
  return userMap.value[userId] || userId
}

onMounted(() => {
  getShiftList()
  fetchUsers()
})
</script>